/*
 * @Author: your name
 * @Date: 2020-11-03 11:00:38
 * @LastEditTime: 2020-11-12 17:26:05
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /crowd-funding/src/api/api.js
 */
import { restApi } from '../utils/restApi'
import { projectId, ErrorType } from '../utils/constants'
import { get } from 'lodash'
import { isUseMockData } from '@/utils/utils' // 判断是否是真实数据
import { storyPageInfoRes, storyPageAdvertInfoRes } from '../mockData/mainMockData'

/**
 * @description: 首页主数据下发
 */
export const storyPageInfo = function () {
	if (isUseMockData()) {
		return Promise.resolve(storyPageInfoRes)
	}
	return restApi({
		functionId: 'storyPageInfo',
		body: {
			projectId,
		},
	})
}

/**
 * @description: 首页广告组下发
 */
export const storyPageAdvertInfo = function () {
	if (isUseMockData()) {
		return Promise.resolve(storyPageAdvertInfoRes)
	}
	return restApi({
		functionId: 'storyPageAdvertInfo',
		body: {
			projectId,
		},
	})
}

export const followProject = function () {
	return restApi({
		functionId: 'followProject',
		body: {
			projectId,
		},
	})
}

/**
 * @description: 首页初始化接口整合
 */
export const initHomeData = function () {
	return Promise.all([storyPageInfo(), storyPageAdvertInfo()])
		.then((result) => {
			for (let i = 0; i < result.length; i++) {
				const resItem = result[i]
				const rtncode = get(resItem, 'rtn_code', -1)
				const code = get(resItem, 'code', -1)
				const biz_code = get(resItem, 'data.biz_code', -1)
				// if (code !== 0) {
				// 	// 接口不通
				// 	return Promise.reject(ErrorType.NO_WIFI_TYPE)
				// }
				if (code !== 0 || rtncode !== 0 || biz_code !== 1000) {
					// 页面无法访问
					return Promise.reject(ErrorType.NO_DATA_TYPE)
				}
			}

			const storyPageRes = get(result[0], 'data.result', { projectStoryNewDto: {} })

			const storyDto = get(result[1], 'data.result.projectAdvertChildInfoVos', [])
			// 将广告组接口下发数据整合到主页下发数据中
			storyPageRes.projectStoryNewDto.storyDto = storyDto
			return Promise.resolve({ storyPageRes })
		})
		.catch((error) => {
			//  ECONNABORTED  timeoutCode
			if (error.code === ErrorType.NO_DATA_TYPE.code) {
				return Promise.reject(error)
			}
			return Promise.reject(ErrorType.NO_WIFI_TYPE)
		})
}
